<template>
    <div class="finance-dashboard">
        <!-- 顶部导航栏 -->
        <div class="top-nav">
            <div class="nav-left">
                <span class="logo">22.com</span>
            </div>
            <div class="nav-right">
                <span class="date">{{ currentDate }}</span>
            </div>
        </div>
        <div class="main-content-wrapper">
            <nav class="nav">
                <div class="nav-links">
                    <p @click="getStockImages(1)" :class="{ linksActive: links === '持仓列表' }">持仓列表</p>
                    <p @click="getStockImages(0)" :class="{ linksActive: links === '观察列表' }">观察列表</p>
                </div>

                <!-- 循环渲染导航链接 -->
                <ul>
                    <li v-for="item in imagesList" :key="item.name">
                        <a
                            href="javascript:void(0)"
                            :class="{ active: activeSection === item.name }"
                            @click="setActiveSection(item.name)"
                        >
                            {{ item.name }}
                        </a>
                    </li>
                    <div class="empty">

                    </div>
                </ul>
            </nav>
            <!-- 主要内容区域 -->
            <div class="main-content">
                <div class="chart-section-item" v-for="item in imagesList" :key="item.name"
                     :id="item.name">
                    <div class="images-content">
                        <div class="images">
                            <div class="yingweicaiqing">
                                <img :src="item.investing" alt="" @click="handleImageClick(item.investing)" style="cursor: pointer;">

                            </div>
                            <div class="percentile">
                                <div>
                                    <!--                                <span>10年PE百分位</span>-->
                                    <img :src="item.pe_img" alt="" @click="handleImageClick(item.pe_img)" style="cursor: pointer;">
                                </div>
                                <div>
                                    <!--                                <span>10年PB百分位</span>-->
                                    <img :src="item.pb_img" alt="" @click="handleImageClick(item.pb_img)" style="cursor: pointer;">
                                </div>
                                <div>
                                    <!--                                <span>10年PS百分位</span>-->
                                    <img :src="item.ps_img" alt="" @click="handleImageClick(item.ps_img)" style="cursor: pointer;">
                                </div>
                                <div>
                                    <!--                                <span>10年PCF百分位</span>-->
                                    <img :src="item.pcf_img" alt="" @click="handleImageClick(item.pcf_img)" style="cursor: pointer;">
                                </div>
                            </div>
                        </div>
                        <div class="text">
                            <p>{{ item.name }} {{item.symbol}} | 市盈率:{{item.pe}} | 股息率:{{item.div_yield}} | 负债率:{{item.debt_ratio}}</p>
                            <p>PE分位点:{{item.pe_per}} | PB分位点:{{item.pb_per}} | PS分位点:{{item.ps_per}} | PCF分位点:{{item.pcf_per}}</p>
                        </div>
                    </div>
                </div>
                <div class="empty">

                </div>
            </div>
        </div>

        <BottomNav/>
        <!-- 图片预览对话框 -->
        <el-image
            v-show="previewDialogVisible"
            :src="previewImage"
            :preview-src-list="[previewImage]"
            initial-index="0"
            fit="contain"
            preview-teleported="true"
            @close="previewDialogVisible = false"
        >
        </el-image>
    </div>
</template>

<script setup>
import {ref, onMounted, onUnmounted} from 'vue'
import BottomNav from '../components/BottomNav.vue'
import {getStockImagesList} from "@/api/stockImages";
import { ElImage } from 'element-plus'
// 这里可以添加响应式数据和方法
const currentDate = ref('')
const imagesList = ref([])
const previewImage = ref('')
const previewDialogVisible = ref(false)
const activeSection = ref('');
const links = ref('持仓列表');
// 格式化当前日期
const formatCurrentDate = () => {
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    const weekday = weekdays[now.getDay()]

    currentDate.value = `今天是${year}年${month}月${day}日 ${weekday}`
}

const getStockImages = (holding) => {
    let data = {
        "holding": holding
    }
    if (holding === 1){
        links.value = '持仓列表'
    }else if (holding === 0){
        links.value = '观察列表'
    }
    getStockImagesList(data).then(res => {
        for (let i = 0; i < res.data.data.items.length; i++) {
            res.data.data.items[i].div_yield = res.data.data.items[i].div_yield+"%"
        }
        imagesList.value = res.data.data.items
    })
}
getStockImages()
// 组件挂载时设置日期
onMounted(() => {
    formatCurrentDate()
})

const handleImageClick = (imageUrl) => {
    previewImage.value = imageUrl
    previewDialogVisible.value = true
    // 强制下一个渲染周期后自动打开预览
    setTimeout(() => {
        const imageElement = document.querySelector('.el-image__inner')
        if (imageElement) {
            imageElement.click()
        }
    }, 10)
}

const setActiveSection = (sectionId) => {
    // 更新活动章节ID
    activeSection.value = sectionId;

    // 找到对应的章节元素
    const section = document.getElementById(sectionId);
    if (section) {
        // 获取导航栏元素以计算其尺寸
        const topNavbar = document.querySelector('.top-nav');
        const mainContent = document.querySelector('.main-content');

        // 计算导航栏高度和主内容区域偏移（添加默认值以防元素未找到）
        const topNavbarHeight = topNavbar ? topNavbar.offsetHeight : 60;
        const mainContentOffset = mainContent ? mainContent.offsetTop : topNavbarHeight;
        const additionalSpace = 10; // 额外间距

        // 计算目标滚动位置，确保与handleScroll逻辑一致
        const targetPosition = section.offsetTop - mainContentOffset + additionalSpace;

        // 平滑滚动到目标位置
        window.scrollTo({
            top: targetPosition,
            behavior: 'smooth'
        });
    }
};

// 处理滚动事件的方法
const handleScroll = () => {
    // 获取导航栏元素以计算其尺寸
    const topNavbar = document.querySelector('.top-nav');
    const leftNav = document.querySelector('.nav');

    // 计算导航栏高度和宽度（添加默认值以防元素未找到）
    const topNavbarHeight = topNavbar ? topNavbar.offsetHeight : 60; // 顶部导航栏高度
    const leftNavWidth = leftNav ? leftNav.offsetWidth : window.innerWidth * 0.15; // 左侧导航栏宽度

    // 获取主内容区域的位置
    const mainContent = document.querySelector('.main-content');
    const mainContentOffset = mainContent ? mainContent.offsetTop : topNavbarHeight;

    // 计算当前滚动位置，考虑导航栏的遮挡
    const scrollPosition = window.pageYOffset;

    // 从后往前遍历章节，找到当前可见的章节
    for (let i = imagesList.value.length - 1; i >= 0; i--) {
        // 获取章节DOM元素
        const section = document.getElementById(imagesList.value[i].name);

        if (section) {
            // 考虑主内容区域的偏移量，确保正确检测可见章节
            const adjustedOffsetTop = section.offsetTop - mainContentOffset;

            // 检查章节是否进入可视区域（顶部边缘超过视口中间位置）
            if (adjustedOffsetTop <= scrollPosition + window.innerHeight * 0.3) {
                // 更新活动章节
                activeSection.value = imagesList.value[i].name;
                // 找到后跳出循环
                break;
            }
        }
    }
};
onMounted(() => {
    window.addEventListener('scroll', handleScroll);
})
onUnmounted(() => {
    window.removeEventListener('scroll', handleScroll);
})
</script>

<style scoped>
.finance-dashboard {
    min-height: 100vh;
    background-color: #f5f7fa;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

/* 顶部导航栏 */
.top-nav {
    background-color: #fff;
    width: 100%;
    z-index: 5;
    height: 60px;
    position: fixed;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.logo {
    font-size: 24px;
    font-weight: bold;
    color: #ff3b30;
}

.date {
    font-size: 14px;
    color: #666;
}

/* 主要内容区域 */
.main-content {
    display: flex;
    margin-top: 60px;
    align-items: center;
    flex-direction: column;
    gap: 30px;
    margin-left: 16%;
}

.chart-section-item {
    background-color: #fff;
    border-radius: 12px;
    padding: 14px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.images-content{
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
}
.images{
    display: flex;
}
.text{
    font-size: 26px;
    font-weight: bold;
    text-align: center;
}
.yingweicaiqing{
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: 70%;
    height: 100%;
}
.yingweicaiqing img{
    max-width: 100%;
    max-height: 100%;
    display: block; /* 防止图片底部出现间隙 */
}
.percentile{
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: 30%;
    height: 100%;
}
/* 平均分配高度给每个直接子div */
.percentile > div {
    position: relative;
}

.percentile img {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
    display: block;
}

.percentile span {
    position: absolute;
    left: 5%;
    top: 20%;
    color: red;
    font-size: 16px;
    font-weight: bold;
}
.main-content-wrapper{
    display: flex;

}
.nav{
    position: fixed;
    width: 15%;
    height: 100%;
    background-color: #fff;
    overflow-y: auto;
    box-shadow: 0 2px 8px rgb(0, 0, 0 ,0.1);
}

.nav ul{
    position: absolute;
    left: 50px;
    top: 120px;
    font-size: 20px;
}
.nav ul li:hover{
    color: #0099ff;
    cursor: pointer;
    transition: all 0.2s;
}
.active {
    color: #0099ff;
}
.empty{
    height: 90px;
}
.nav-links{
    display: flex;
    gap: 20px;
    justify-content: center;
    width: 100%;
    margin-left: 50%;
    margin-top: 75px;
    margin-bottom: 75px;
    transform: translateX(-50%);
    font-size: 20px;
}
.nav-links p{
    margin-bottom: 10px;
    cursor: pointer;
}

.nav-links p:hover{
    border-bottom: 2px solid #3fabf5;
}
.linksActive{
    color: #3fabf5;
    border-bottom: 2px solid #3fabf5;
}



@keyframes drawChart {
    0% {
        width: 0;
    }
    100% {
        width: 100%;
    }
}

/* 响应式设计 */
@media (max-width: 768px) {
    .main-content {
        padding: 0px;
    }

    /* 顶部导航栏 */
    .top-nav {
        padding: 0 16px;
        height: 50px;
    }

    .logo {
        font-size: 20px;
    }

    .date {
        font-size: 12px;
    }

    /* 图表区域 */
    .chart-section {
        padding: 0px;
        margin-bottom: 16px;
    }

}

@media (max-width: 480px) {
}
</style>
